<script>
import HModal from '@comp/hhd/HModal/HModal.vue'
import ButtonRegistry from '@comp/hhd/design/FormMenu/button/ButtonRegistry'
import { createProps } from '@/utils'
import { createFormDefinition } from '@comp/hhd/design/FormDesigner/types'

export default {
  name: 'ButtonConfigModal',
  components: {
    HModal
  },
  props: {
    menu: createProps(Object, () => undefined),
    formDefinition: createProps(Object, createFormDefinition)
  },
  data() {
    return {
      button: undefined,
      buttonConfig: undefined,
      visible: false
    }
  },
  render(h) {
    if (!this.buttonConfig) return undefined
    let config = ButtonRegistry[this.buttonConfig.buttonComponent] && ButtonRegistry[this.buttonConfig.buttonComponent].config
    if (!config) return

    return h(HModal, {
      attrs: {
        okText: '确定',
        cancelText: '取消'
      },
      props: {
        config: this.buttonConfig,
        title: '按钮配置',
        visible: this.visible,
        width: 800,
        height: 600
      },
      on: {
        ok: () => this.handleOK(),
        cancel: () => this.close()
      }
    }, this.renderConfigComponent(h, config))
  },
  methods: {
    renderConfigComponent(h, configComponent) {
      return [h(configComponent, {
        ref: 'config',
        props: {
          button: this.buttonConfig,
          config: this.buttonConfig.config,
          menu: this.menu,
          formDefinition: this.formDefinition
        }
      })]
    },
    handleOK() {
      if (!this.$refs.config.check()) return
      this.$emit('ok', this.buttonConfig)
      this.close()
    },
    setData(buttonConfig, button) {
      this.buttonConfig = buttonConfig
      this.$nextTick(() => {
        this.open()
      })
    },
    open() {
      this.visible = true
    },
    close() {
      this.visible = false
    }
  }
}
</script>